package com.zsrd.self.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/4/11 9:23
 */
public class SaltEncryption {

    public static String encrypt(String data, String salt)throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCs5Padding");
        SecretKeySpec secretKey = new SecretKeySpec(salt.getBytes(),"AES");
        cipher.init(cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedData, String salt)throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKey = new SecretKeySpec(salt.getBytes(),"AES");
                cipher.init(cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes);
    }

}
